from flask import request, current_app
from flask_restx import Resource, Namespace, fields
from app.services.user_photo_service import UserPhotoService
from app.utils.auth import user_token_required
from app.utils.response import success_response, error_response
from app.utils.validators import validate_required_fields
from . import api

# 创建命名空间
photos_ns = Namespace('photos', description='用户照片管理')

# 定义请求模型
add_photo_model = photos_ns.model('AddPhoto', {
    'file_id': fields.Integer(required=True, description='文件ID'),
    'is_avatar': fields.Boolean(description='是否设置为头像', default=False)
})

update_photo_model = photos_ns.model('UpdatePhoto', {
    'is_avatar': fields.Boolean(description='是否设置为头像'),
    'sort_order': fields.Integer(description='排序')
})

sort_photos_model = photos_ns.model('SortPhotos', {
    'photos': fields.List(fields.Nested(photos_ns.model('PhotoOrder', {
        'id': fields.Integer(required=True, description='照片ID'),
        'sort_order': fields.Integer(required=True, description='排序')
    })), required=True, description='照片排序列表')
})

@photos_ns.route('/photos')
class UserPhotosAPI(Resource):
    """用户照片列表接口"""
    
    @user_token_required
    def get(self, current_user):
        """获取用户照片列表"""
        try:
            photos = UserPhotoService.get_user_photos(current_user.id)
            return success_response(photos, '获取成功')
        except Exception as e:
            current_app.logger.error(f"获取用户照片异常: {str(e)}")
            return error_response(f"获取失败: {str(e)}", 500)
    
    @photos_ns.expect(add_photo_model)
    @user_token_required
    def post(self, current_user):
        """关联照片到用户"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['file_id'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            file_id = data.get('file_id')
            is_avatar = data.get('is_avatar', False)
            
            # 添加照片
            photo = UserPhotoService.add_user_photo(current_user.id, file_id, is_avatar)
            return success_response(photo, '照片添加成功')
        except Exception as e:
            current_app.logger.error(f"添加用户照片异常: {str(e)}")
            return error_response(f"添加失败: {str(e)}", 500)


@photos_ns.route('/photos/<int:photo_id>')
class UserPhotoAPI(Resource):
    """单个用户照片接口"""
    
    @photos_ns.expect(update_photo_model)
    @user_token_required
    def put(self, photo_id, current_user):
        """更新照片信息"""
        try:
            data = request.get_json() or {}
            is_avatar = data.get('is_avatar')
            sort_order = data.get('sort_order')
            
            # 更新照片信息
            photo = UserPhotoService.update_photo_info(
                current_user.id, photo_id, is_avatar, sort_order
            )
            return success_response(photo, '更新成功')
        except Exception as e:
            current_app.logger.error(f"更新照片信息异常: {str(e)}")
            return error_response(f"更新失败: {str(e)}", 500)
    
    @user_token_required
    def delete(self, photo_id, current_user):
        """删除照片关联"""
        try:
            success = UserPhotoService.delete_user_photo(current_user.id, photo_id)
            if success:
                return success_response(message='照片删除成功')
            else:
                return error_response('照片不存在或删除失败', 400)
        except Exception as e:
            current_app.logger.error(f"删除照片异常: {str(e)}")
            return error_response(f"删除失败: {str(e)}", 500)


@photos_ns.route('/photos/sort')
class PhotosSortAPI(Resource):
    """照片排序接口"""
    
    @photos_ns.expect(sort_photos_model)
    @user_token_required
    def put(self, current_user):
        """照片排序"""
        try:
            # 验证必填字段
            is_valid, error_msg = validate_required_fields(['photos'])
            if not is_valid:
                return error_response(error_msg, 400)
            
            data = request.get_json()
            photo_orders = data.get('photos', [])
            
            # 执行排序
            sorted_photos = UserPhotoService.sort_user_photos(current_user.id, photo_orders)
            return success_response(sorted_photos, '排序成功')
        except Exception as e:
            current_app.logger.error(f"照片排序异常: {str(e)}")
            return error_response(f"排序失败: {str(e)}", 500)


@photos_ns.route('/photos/<int:photo_id>/avatar')
class SetAvatarAPI(Resource):
    """设置头像接口"""
    
    @user_token_required
    def put(self, photo_id, current_user):
        """设置头像"""
        try:
            photo = UserPhotoService.set_avatar(current_user.id, photo_id)
            return success_response(photo, '头像设置成功')
        except Exception as e:
            current_app.logger.error(f"设置头像异常: {str(e)}")
            return error_response(f"设置失败: {str(e)}", 500)


# 将命名空间注册到API实例
api.add_namespace(photos_ns) 